package repositories

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"log"
	"signature-service/global"
)

type PrivateKeys struct {
	ID         string `bson:"_id,omitempty" json:"id"`
	Address    string `bson:"address" json:"address"`
	PrivateKey string `bson:"private_key" json:"private_key"`
	Type       string `bson:"type" json:"type"`
}

// Insert 插入数据
func (s *PrivateKeys) Insert() error {
	id, err := global.DBEngine.Database(global.DBName).Collection("private_key").InsertOne(context.TODO(), s)
	if err == nil {
		s.ID = id.InsertedID.(primitive.ObjectID).Hex()
	}
	return err
}

// FindOne 查询单条数据
func (s *PrivateKeys) FindOne() error {
	id, err := primitive.ObjectIDFromHex(s.ID)
	if err != nil {
		return err
	}
	client := global.DBEngine.Database(global.DBName).Collection("private_key")
	filter := bson.M{"_id": id}
	err = client.FindOne(context.TODO(), filter).Decode(&s)
	return err
}

// FindAll 查询所有数据
func (s *PrivateKeys) FindAll() ([]PrivateKeys, error) {
	client := global.DBEngine.Database(global.DBName).Collection("private_key")
	filter := bson.M{}
	cursor, err := client.Find(context.Background(), filter)
	if err != nil {
		return nil, err
	}
	var result []PrivateKeys
	err = cursor.All(context.Background(), &result)
	return result, err
}

// Update 更新数据
func (s *PrivateKeys) Update() error {
	id, err := primitive.ObjectIDFromHex(s.ID)
	if err != nil {
		return err
	}
	client := global.DBEngine.Database(global.DBName).Collection("private_key")
	filter := bson.M{"_id": id}
	update := bson.M{"$set": bson.M{"private_key": s.PrivateKey}}
	_, err = client.UpdateOne(context.TODO(), filter, update)
	return err
}

// BatchUpdate 批量更新
func (s *PrivateKeys) BatchUpdate(models []mongo.WriteModel) error {
	client := global.DBEngine.Database(global.DBName).Collection("private_key")
	_, err := client.BulkWrite(context.TODO(), models)
	if err != nil {
		log.Printf("Bulk update error: %v", err)
		return err
	}
	return nil
}
